package com.demo.las.service;

import com.demo.las.entity.MajorReport;
import com.demo.las.repository.MajorReportRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MajorReportService {

    private final Path uploadRoot = Paths.get(System.getProperty("user.dir"), "uploads", "major_reports");

    @Autowired
    private MajorReportRepository majorReportRepository;

    private void ensureUploadDir() throws IOException {
        if (!Files.exists(uploadRoot)) {
            Files.createDirectories(uploadRoot);
        }
    }

    private String sanitize(String input) {
        if (input == null) return "";
        return input.replaceAll("[^\\p{L}\\p{N}]", "");
    }

    private String getFileExtension(String filename) {
        if (filename == null) return "";
        int dot = filename.lastIndexOf('.');
        return dot >= 0 ? filename.substring(dot) : "";
    }

    public MajorReport saveUpload(String studentName, String studentNo, String className, String courseName, LocalDate submitDate, MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        ensureUploadDir();

        String original = file.getOriginalFilename();
        String ext = getFileExtension(original);
        String safeName = sanitize(studentName);
        String safeNo = sanitize(studentNo);
        String timestamp = String.valueOf(System.currentTimeMillis());
        String newFileName = safeNo + "_" + safeName + "_" + timestamp + ext;

        Path target = uploadRoot.resolve(newFileName);
        Files.copy(file.getInputStream(), target, StandardCopyOption.REPLACE_EXISTING);

        MajorReport report = new MajorReport();
        report.setStudentName(studentName);
        report.setStudentNo(studentNo);
        report.setOriginalFileName(original);
        report.setFileName(newFileName);
        report.setFileUrl("/major_reports/" + newFileName);
        report.setClassName(className);
        report.setCourseName(courseName);
        report.setSubmitDate(submitDate);
        report.setUploadTime(LocalDateTime.now());

        return majorReportRepository.save(report);
    }

    public List<MajorReport> search(String studentName, String studentNo, String className, String courseName, LocalDate submitDate) {
        List<MajorReport> all = majorReportRepository.findAll();
        return all.stream()
                .filter(r -> studentName == null || studentName.isBlank() || (r.getStudentName() != null && r.getStudentName().contains(studentName)))
                .filter(r -> studentNo == null || studentNo.isBlank() || (r.getStudentNo() != null && r.getStudentNo().contains(studentNo)))
                .filter(r -> className == null || className.isBlank() || (r.getClassName() != null && r.getClassName().contains(className)))
                .filter(r -> courseName == null || courseName.isBlank() || (r.getCourseName() != null && r.getCourseName().contains(courseName)))
                .filter(r -> submitDate == null || r.getSubmitDate() == null || r.getSubmitDate().isEqual(submitDate))
                .sorted((a, b) -> b.getUploadTime().compareTo(a.getUploadTime()))
                .collect(Collectors.toList());
    }

    public List<MajorReport> listAll() {
        return majorReportRepository.findAll();
    }
}